package com.yuntoyun.codeavatar.app.fwcore.plug.pay.wxpay;

import android.content.Context;

import com.google.gson.JsonObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yuntoyun.fwcore.config.FwAppConfig;

/**
 * 微信支付插件
 * <p>
 * 下载地址：https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=11_1
 */
public class PlugWxpay {

    public static WxCallback wxCallback;

    /**
     * 接口示例：https://wxpay.wxutil.com/pub_v2/app/app_pay.php
     * 数据格式：
     {
     "appid": "wxb4ba3c02aa476ea1",
     "noncestr": "39acc801e6f498ebe075769b8ce36d78",
     "package": "Sign=WXPay",
     "partnerid": "1900006771",
     "prepayid": "wx2011524958404244ce424d311776620802",
     "sign": "E58EFB13134F1D4F778F0E85CFEF6471",
     "timestamp": 1537415569
     }
     * @param context
     */

    /**
     * 微信支付
     *
     * @param context
     * @param joWxdata
     * @param extData
     */
    public void pay(Context context, JsonObject joWxdata, String extData, WxCallback callback) {
        //用于回调
        wxCallback = callback;

        IWXAPI api = WXAPIFactory.createWXAPI(context, FwAppConfig.WECHAT_APPID);
        PayReq req = new PayReq();
        req.appId = joWxdata.get("appid").getAsString();
        req.partnerId = joWxdata.get("partnerid").getAsString();
        req.prepayId = joWxdata.get("prepayid").getAsString();
        req.nonceStr = joWxdata.get("noncestr").getAsString();
        req.timeStamp = joWxdata.get("timestamp").getAsString();
        req.packageValue = joWxdata.get("package").getAsString();
        req.sign = joWxdata.get("sign").getAsString();
        req.extData = extData; // optional
        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        api.sendReq(req);
    }
}
